package cn.edu.sctu.sctu_lysd.view.act;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.edu.sctu.sctu_lysd.R;
import cn.edu.sctu.sctu_lysd.adapter.PhotoGridViewAdapter;
import cn.edu.sctu.sctu_lysd.base.BaseActivity;
import cn.edu.sctu.sctu_lysd.bean.FolderBean;
import cn.edu.sctu.sctu_lysd.utils.CacheImgPathUtil;


/**
 * Created by 鑫爷您慢点 on 2016/8/3.
 */
public class PhotoActivity extends BaseActivity {
    private GridView mGridView;
    private List<String> mImgs;
    private PhotoGridViewAdapter mImageAdapter;

    private RelativeLayout mBottomLy;
    private TextView mDirName, mDirCount;
    private File mCurrentDir;
    private RelativeLayout mYulan;
    private TextView mSubmitTxt;
    private TextView mReturnTxt;
    private int mMaxCount;
    private final int DATA_LOADED_FINISH = 0x110;

    private ListImageDirPopupWindow mDirPopupWindow;

    private ArrayList<String> mSelectedImgPath;

    private List<FolderBean> mFolderBeans = new ArrayList<FolderBean>();

    public static final String IMAGE_PATH_INTENT_FLAG = "img_path";


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == DATA_LOADED_FINISH) {

                dataToView();
                initDirPopupWindow();
            }
        }
    };

    @Override
    protected int getLayoutResource() {
        return R.layout.photo_main;
    }

    @Override
    protected void initAfter(Object bind) {

        initView();
        initData();
        initEvent();

    }

    @Override
    protected void onStop() {
        super.onStop();
        mSelectedImgPath = null;
    }

    private void initDirPopupWindow() {
        mDirPopupWindow = new ListImageDirPopupWindow(this, mFolderBeans);
        mDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                lightOn();
            }
        });
        mDirPopupWindow.setOnDirSelectedListener(new ListImageDirPopupWindow.OnDirSelectedListener() {
            @Override
            public void onSelected(FolderBean folderBean) {
                mCurrentDir = new File(folderBean.getDir());
                mImgs = Arrays.asList(mCurrentDir.list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png"))
                            return true;
                        return false;
                    }
                }));
                mImageAdapter = new PhotoGridViewAdapter(PhotoActivity.this, mImgs, mCurrentDir.getAbsolutePath(),false);

                mGridView.setAdapter(mImageAdapter);

                mDirCount.setText(mImgs.size() + "");
                mDirName.setText(folderBean.getName());

                mDirPopupWindow.dismiss();
            }
        });
    }


    private void initView() {

        mGridView = (GridView) findViewById(R.id.id_gridView);
        mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);
        mDirName = (TextView) findViewById(R.id.id_dir_name);
        mDirCount = (TextView) findViewById(R.id.id_dir_count);

        mReturnTxt = (TextView) findViewById(R.id.id_select_photo_back_txt);
        mYulan = (RelativeLayout) findViewById(R.id.id_dir_yulan);
        mSubmitTxt = (TextView) findViewById(R.id.id_select_photo_submit);

    }

    /**
     * 内容区域变亮
     */
    private void lightOn() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f;
        getWindow().setAttributes(lp);
    }

    /**
     * 内容区域变暗
     */
    private void lightOff() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = .3f;
        getWindow().setAttributes(lp);
    }

    /**
     * 将数据绑定到View
     */
    private void dataToView() {
        if (mCurrentDir == null) {
            Toast.makeText(this, "未扫描到任何图片", Toast.LENGTH_SHORT).show();
            return;
        }

        mImgs = Arrays.asList(mCurrentDir.list());
        mImageAdapter = new PhotoGridViewAdapter(this, mImgs, mCurrentDir.getAbsolutePath(),false);
        mGridView.setAdapter(mImageAdapter);

        mDirCount.setText(mMaxCount + "");
//        mDirName.setText(mCurrentDir.getName());

    }

    private void initEvent() {
        mBottomLy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDirPopupWindow.setAnimationStyle(R.style.dir_popupwindow_anim);
                mDirPopupWindow.showAsDropDown(mBottomLy, 0, 0);
                lightOff();
            }

        });
        mYulan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 回调所选中的图片路径set
                 */
                mSelectedImgPath = new ArrayList<String>();
                mImageAdapter.setGetSelectedPhotoPath(new GetSelectedPhotoPath() {
                    @Override
                    public void getSelectedPhotoPath(Set<String> selectedImg) {
                        for (String str : selectedImg) {
                            mSelectedImgPath.add(str);
                        }
                    }
                });
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("selectedImgPath", mSelectedImgPath);

                //TODO 预览选择后的图片
//                JumpUtils.jumpActivity(PhotoActivity.this, ShowSelectedPhotoActivity.class, bundle);
            }
        });

        mSubmitTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 回调所选中的图片路径set
                 */
                mSelectedImgPath = new ArrayList<String>();
                mImageAdapter.setGetSelectedPhotoPath(new GetSelectedPhotoPath() {
                    @Override
                    public void getSelectedPhotoPath(Set<String> selectedImg) {
                        /**
//                         * 回掉图片路径
//                         */
//                        CacheImgPathUtil.getInstance(PhotoActivity.this).setCacheImgPath(selectedImg);

                        for (String str : selectedImg) {
                            mSelectedImgPath.add(str);
                        }

                    }
                });


                Intent intent = new Intent(PhotoActivity.this,GoodsMessageAct.class);

                Bundle bundle = new Bundle();

                bundle.putStringArrayList(IMAGE_PATH_INTENT_FLAG,mSelectedImgPath);

                intent.putExtras(bundle);

                setResult(RESULT_OK,intent);

                finish();

            }
        });

        mReturnTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               finish();

            }
        });

    }

    /**
     * 利用ContentProvider扫描手机中的图片
     */
    private void initData() {
        /**
         * 1、判断存储卡是否可用
         */
        //判断外部存储卡
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "当前存储卡不可用", Toast.LENGTH_SHORT).show();
            return;
        }
//        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");

        /**
         * 2、开启线程扫描图片
         */
        new Thread() {
            @Override
            public void run() {
                Uri mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver cr = PhotoActivity.this.getContentResolver();


                // 只查询jpeg和png的图片
                Cursor cursor = cr.query(mImgUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);//DATE_MODIFIED 排序

                //  一个文件下有多张图片  set  防止重复扫描
                Set<String> mDirPathSet = new HashSet<String>();
                /**
                 * 遍历游标  拿到所有图片路径 ，再通过所有图片拿到它所属文件夹
                 */
                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    File parentFile = new File(path).getParentFile();//拿到每个图片的所属文件夹
                    if (parentFile == null) continue;
                    String dirPath = parentFile.getAbsolutePath();//拿到文件夹路径

                    FolderBean folderBean = null;

                    if (mDirPathSet.contains(dirPath)) {//防止重复扫描
                        continue;
                    } else {
                        mDirPathSet.add(dirPath);
                        folderBean = new FolderBean();
                        folderBean.setDir(dirPath);
                        folderBean.setFirstImgPath(path);

                    }

                    if (parentFile.list() == null) continue;

                    int picSize = parentFile.list(new FilenameFilter() {//过滤图片
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".png"))
                                return true;
                            return false;
                        }
                    }).length;
                    folderBean.setCount(picSize);

                    mFolderBeans.add(folderBean);//mFolderBeans  用于初始化底部popwindow值

                    if (picSize > mMaxCount) {
                        mMaxCount = picSize;
                        mCurrentDir = parentFile;
                    }
                }
                cursor.close();
                //通知handler扫描图片完成
                mHandler.sendEmptyMessage(DATA_LOADED_FINISH);
            }
        }.start();
    }


    public interface GetSelectedPhotoPath {
        void getSelectedPhotoPath(Set<String> mSelectedImg);
    }

}
